package com.tuni.birthdaymoney.web.controller;

import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.tuni.birthdaymoney.persistence.entity.Person;
import com.tuni.birthdaymoney.service.PersonService;
import com.tuni.birthdaymoney.web.model.MasterPage;
import com.tuni.birthdaymoney.web.model.SubscriptionPage;

@Controller
public class SubscriptionController {
    
    @Autowired
    private PersonService personService;
    
    @RequestMapping(value = "/unsubscribe/{authToken}", method = RequestMethod.GET)
    public String unsubscribe(@PathVariable("authToken")String authToken,
            Map<String, Object> subscriptionPageMap) {
        // Anonymous access to unsubscribe feature
        MasterPage masterPageModel = new MasterPage(null, true);
        subscriptionPageMap.put("masterPageModel", masterPageModel);
        SubscriptionPage subscriptionPageModel = new SubscriptionPage();
        Person personToUnsubscribe = personService.getByAuthToken(authToken);
        if (personToUnsubscribe != null) {
            if (personToUnsubscribe.isWantToReceive()) {
                personToUnsubscribe.setWantToReceive(false);
                personService.update(personToUnsubscribe);
                subscriptionPageModel.setMessage("You are successfully unsubscribed.");
            } else {
                subscriptionPageModel.setMessage("You are not subscribed.");
            }
        } else {
            subscriptionPageModel.setMessage("Subscription link appears to be broken.");
        }
        subscriptionPageMap.put("subscriptionPageModel", subscriptionPageModel);
        return "subscription";
    }
}
